const params = {
    pagenum: 1,
    pagesize: 2,
    cate_id: '',
    state: ''
}
// 定义美化时间的过滤器
template.defaults.imports.dataFormat = function (date) {
    const dt = new Date(date)

    var y = dt.getFullYear()
    var m = padZero(dt.getMonth() + 1)
    var d = padZero(dt.getDate())

    var hh = padZero(dt.getHours())
    var mm = padZero(dt.getMinutes())
    var ss = padZero(dt.getSeconds())

    return y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
}
// 定义补零的函数
function padZero(n) {
    return n > 9 ? n : '0' + n
}


$(function () {
    getArticleList();
    getCateList();
    // 筛选
    $('#selectForm').on('submit', function (e) {
        e.preventDefault();
        params.cate_id = $('[name=cate_id]').val();
        params.state = $('[name=state]').val();
        getArticleList();
    });

    // 删除
    $('body').on('click', '.deleteCate', function () {
        const id = $(this).attr('data-id');
        layer.confirm('确认要删除?', { icon: 3, title: '提示' }, function (index) {
            $.ajax({
                type: "GET",
                url: `/my/article/delete/${ id }`,
                success: function (response) {
                    if (response.status !== 0) return layer.msg('删除失败!');
                    layer.msg('删除成功!');

                    if ($('tbody tr').length === 1 && params.pagenum !== 1) {
                        params.pagenum = params.pagenum - 1;
                    }

                    getArticleList();
                }
            });
            layer.close(index);
        });
    })
})

// 获取文章列表数据
function getArticleList() {
    $.ajax({
        type: "GET",
        url: "/my/article/list",
        data: params,
        success: function (response) {
            if (response.status !== 0) return layer.msg('获取数据失败!');
            const htmlString = template('tpl-list', response);
            $('tbody').html(htmlString);

            //执行一个laypage实例 分页
            layui.laypage.render({
                elem: 'test1', //注意，这里的 test1 是 ID，不用加 # 号
                count: response.total, //数据总数，从服务端得到
                limit: params.pagesize,
                layout: ['count', 'limit', "prev", "page", "next", 'skip'],
                curr: params.pagenum,
                limits: [1, 2, 5],
                // 当分页被切换时触发
                jump: function (obj, first) {
                    params.pagenum = obj.curr;
                    params.pagesize = obj.limit;
                    if (!first) {
                        getArticleList();
                    }
                }
            });
        }
    });
}

// 获取下拉框数据
function getCateList() {
    $.ajax({
        type: "GET",
        url: "/my/article/cates",
        success: function (response) {
            if (response.status !== 0) return layer.msg('获取失败!');
            const htmlStr = template('tpl-cate', response);
            $('[name=cate_id]').html(htmlStr);
            // 对layui插件更新一下数据
            layui.form.render();
        }
    });
}